package com.yipin.neimeng.util;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;

import java.io.IOException;
import java.net.SocketTimeoutException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
public class OkHttpUtils {

    private static OkHttpClient okHttpClient = null;
    private static final MediaType JSON_MEDIA_TYPE = MediaType.parse("application/json; charset=utf-8");

    // 私有构造函数，禁止外部实例化
    private OkHttpUtils() {
    }

    public static OkHttpClient getOkHttpClient() {
        if (okHttpClient == null) {
            synchronized (OkHttpUtils.class) {
                if (okHttpClient == null) {
                    ConnectionPool connectionPool = new ConnectionPool(50, 10, TimeUnit.MINUTES);
                    okHttpClient = new OkHttpClient.Builder()
                            .connectTimeout(10, TimeUnit.SECONDS)
                            .writeTimeout(20, TimeUnit.SECONDS)
                            .readTimeout(20, TimeUnit.SECONDS)
                            .connectionPool(connectionPool)
                            .build();
                }
            }
        }
        return okHttpClient;
    }

    /**
     * 同步GET请求
     *
     * @param url 请求地址
     * @return 响应内容字符串
     * @throws RuntimeException 如果请求失败或超时
     */
    public static String getRequest(String url) {
        try {
            Request request = new Request.Builder()
                    .get()
                    .url(url)
                    .build();
            Response response = getOkHttpClient().newCall(request).execute();
            if (response.isSuccessful()) {
                return response.body().string();
            } else {
                throw new RuntimeException("请求异常,错误码为: " + response.code());
            }
        } catch (SocketTimeoutException e) {
            log.error("GET请求超时: {}", e.getMessage(), e);
            throw new RuntimeException("GET请求超时", e);
        } catch (IOException e) {
            log.error("GET请求异常: {}", e.getMessage(), e);
            throw new RuntimeException("GET请求异常", e);
        }
    }

    /**
     * 同步POST请求
     *
     * @param url     请求地址
     * @param headers 请求头
     * @param params  请求参数（Map将转换为JSON）
     * @return 响应内容字符串
     * @throws RuntimeException 如果请求失败或超时
     */
    public static String postRequest(String url, Map<String, Object> headers, Map<String, Object> params) {
        try {
            String json = JSON.toJSONString(params); // 使用Fastjson将Map转换为JSON字符串
            RequestBody body = RequestBody.create(JSON_MEDIA_TYPE, json);

            Request.Builder requestBuilder = new Request.Builder()
                    .url(url)
                    .post(body);

            if (headers != null && !headers.isEmpty()) {
                for (Map.Entry<String, Object> header : headers.entrySet()) {
                    requestBuilder.header(header.getKey(), String.valueOf(header.getValue()));
                }
            }

            Request request = requestBuilder.build();
            Response response = getOkHttpClient().newCall(request).execute();

            if (response.isSuccessful()) {
                return response.body().string();
            } else {
                throw new RuntimeException("请求异常,错误码为: " + response.code());
            }
        } catch (SocketTimeoutException e) {
            log.error("POST请求超时: {}", e.getMessage(), e);
            throw new RuntimeException("POST请求超时", e);
        } catch (IOException e) {
            log.error("POST请求失败: {}", e.getMessage(), e);
            throw new RuntimeException("POST请求失败", e);
        }
    }

    /**
     * 同步POST请求
     *
     * @param url     请求地址
     * @param json    请求参数（JSON字符串）
     * @param headers 请求头
     * @return 响应内容字符串
     * @throws RuntimeException 如果请求失败或超时
     **/
    public static String postRequest(String url, String json, Map<String, Object> headers) {
        try {
            RequestBody body = RequestBody.create(JSON_MEDIA_TYPE, json);

            Request.Builder requestBuilder = new Request.Builder()
                    .url(url)
                    .post(body);

            // 添加请求头
            if (headers != null && !headers.isEmpty()) {
                for (Map.Entry<String, Object> header : headers.entrySet()) {
                    requestBuilder.header(header.getKey(), String.valueOf(header.getValue()));
                }
            }

            Request request = requestBuilder.build();
            Response response = getOkHttpClient().newCall(request).execute();

            if (response.isSuccessful()) {
                return response.body().string();
            } else {
                throw new RuntimeException("请求异常,错误码为: " + response.code());
            }
        } catch (SocketTimeoutException e) {
            log.error("POST请求超时: {}", e.getMessage(), e);
            throw new RuntimeException("POST请求超时", e);
        } catch (IOException e) {
            log.error("POST请求失败: {}", e.getMessage(), e);
            throw new RuntimeException("POST请求失败", e);
        }
    }
}
